package mall

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/mall"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MallSiteEditLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewMallSiteEditLogic - 添加/编辑站点
func NewMallSiteEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MallSiteEditLogic {
	return &MallSiteEditLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MallSiteEditLogic) MallSiteEdit(req *types.MallSiteEdit) error {
	// 创建实例
	mallSiteDao := mall.NewMallSiteDao(l.ctx, l.svcCtx)

	// 组装参数
	brandSiteInfo := &ent.HzMallSite{
		MallSiteIcon: req.MallSiteIcon,
		MallSiteName: req.MallSiteName,
		MallSiteSort: req.MallSiteSort,
		MallSiteShow: req.MallSiteShow,
		UpdateAt:     time.Now().Unix(),
	}

	// 新增站点信息
	if req.Type == constant.Add {
		brandSiteInfo.CreatedAt = time.Now().Unix()
		if err := mallSiteDao.MallSiteCreate(brandSiteInfo, nil); err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("添加站点失败: %v", err))
		}
	}

	// 编辑站点信息
	if req.Type == constant.Edit && req.Id != 0 {
		brandSiteInfo.ID = int(req.Id)
		if err := mallSiteDao.MallSiteUpdate(brandSiteInfo, nil); err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("修改站点失败: %v", err))
		}
	}

	return nil
}
